<template>
    <view class="uni-container-calender">
        <div class='cale-header Ellipsis'>{{merchDetail.title}}</div>
        <div class="cale-content">
           <div class="recomd-wapper">
               <scroll-view class="selectionTab"
                scroll-x="true" @scroll="scroll" @scrolltolower="scrolltolower" :scroll-left='tabScrollLeft'>
                    <view
                        v-for="(item, index) in data"
                        class="scroll-view-item_H"
                        :class="{Tabactive:tabActiveIndex == index}"
                        @tap="switchBar(item, index)"
                        :key="item.day"
                    >
                    {{item.yearSimple}}年{{item.month}}月
                    </view>
                </scroll-view>
           </div>
           <div class="cale-detail">
               <span 
                    v-for="k in 7" :key="k"
                    class="cell cale-week"
                    :class="{weekStyle:k==0||k==6}"
                >
                    {{weekDays[k]}}
                </span>
                <ul class="cale-list clearfix">
                    <li 
                    class="cale-li fl" 
                    v-for="(item,i) in showData"  
                    :key="i" 
                    @click="selectDays(item,i)"
                    :class="[
                        {disable:item.disable},
                        {weekStyle:!item.disable&&(item.week==0||item.week ==6)},
                        {activeCela:selectIndex==i}
                    ]">
                        <span class="cell" v-if="item.day !== -1">{{item.day}}</span>
                        <span class="price" v-if="item.price !==-1&&item.day !==-1">¥{{isVIP?item.vipPrice:item.price}}</span>
                        <span class='soldOut'  v-if="item.price !==-1&&item.day !==-1">{{item.inventory?'余'+item.inventory:'已售完'}}</span>
                    </li>
                </ul>
           </div>
        </div>
        <div class="cale-buy-container" v-if="canSelect">
            <h3>选择数量</h3>
            <div class='cale-count'>
                <span class='cale-price' v-if="!isVIP">
                   成人<span class='cale-buy-price'>¥{{selectItem?Number(selectItem.price)*Number(selectNum):0}}</span>
                   <span class='cale-buy-vipPrice' >会员价¥{{selectItem?Number(selectItem.vipPrice)*Number(selectNum):0}}</span>
                </span>
                <span class='cale-price' v-if="isVIP">
                   成人<span class='cale-buy-price'>¥{{selectItem?Number(selectItem.vipPrice)*Number(selectNum):0}}</span>
                   <span class='cale-buy-vip'><span class="vip-icon">会员价</span><span class="original-price">原价¥{{selectItem?Number(selectItem.price)*Number(selectNum):0}}</span></span>
                </span>
                <span class='cale-goods-num'>
                    <i class='minus-icon' @tap='minusNum'>-</i>
                    <span class='num'>{{selectNum}}</span>
                    <i class="add-icon" @tap='addNum' :style="{color:selectNum==selectItem.inventory?'rgba(119, 119, 119,.4)':'rgba(119, 119, 119,.8)'}">+</i>
                </span>
            </div>
        </div>
        <VIPCard v-if="canSelect"></VIPCard>
        <div class='cale-footer' v-if="canSelect">
            <span class='cale-select-info'>已选择：{{selectItem.month < 10 ? `0${selectItem.month}`:selectItem.month}}-{{selectItem.day < 10 ? `0${selectItem.day}`:selectItem.day}}出发/成人*{{selectNum}}</span>
            <span class='cale-next-btn' @tap='fillOrder'>确认选择，下一步</span>
        </div>
    </view>
</template>
<script>
import {mapState,mapMutations} from 'vuex';
import VIPCard from '../../components/vipCard';
export default {
    computed: {
        ...mapState(['hasLogin', 'isVIP','merchInfoForOrder'])
    },
    components: {
        VIPCard,
    },
    data(){
        return{
            merchId:0,
            data:[],
            merchDetail:null,
            tabActiveIndex:-1,
            weekDays:['日','一','二','三','四','五','六'],
            showData:[],
            selectIndex:-1,
            activeYearMonth:{
                year:0,
                month:0,
            },
            selectItem:null,
            defaultStartDate:null,
            selectNum:1,
            canSelect:false,//是否有可选日期
            firstEnter:true,
            tabScrollLeft:'100%'
        }
    },
    mounted() {
        this.merchCalendar(0); 
    },
    onLoad(options){
        this.merchId = options.merchId;
    },
    onShow() {
        this.setPeopleCheckList(null);
    },
    methods: {
        ...mapMutations(['setCaleIndfo','setPeopleCheckList']),
        switchBar(item, i){
            this.tabActiveIndex = i;
            this.showFun(this.data,i);
        },
        selectDays(item,i){//选择日期
            if(item.disable){
                return;
            }
            this.selectIndex = i;
            this.selectItem = item;
        },
        minusNum(){
            this.selectNum>1&&
            this.selectNum--;
        },
        addNum(){
            this.selectNum<this.selectItem.inventory&&this.selectNum++;
        },
        getMonthDay(year, month) {
            let days = new Date(year, month, 0).getDate()
            return days;
        },
        getFirstWeekDay(){//获取每个月第一天周几
            let {year,month} = this.getYearMonthDay(this.getDate(this.activeYearMonth.year,this.activeYearMonth.month,1));
            let currentFirstDay = this.getDate(year,month-1,1);
            let week = currentFirstDay.getDay();
            if(week !== 0){
                for(let i=0;i<week;i++){
                    this.showData.unshift({
                        day:-1,
                        disable:true,
                        price:-1
                    })
                }
            }
        },
        makeMonthDya(index){
            this.canSelect = false;
            let days = this.getMonthDay(this.activeYearMonth.year,this.activeYearMonth.month);
            let prevDta = [],backData = [];
            for(let i=1;i<this.showData[0].day;i++){
                prevDta.push({
                    day:i,
                    disable:true,
                    price:-1
                })
            }
            this.showData = prevDta.concat(this.showData);
            if(this.showData[this.showData.length-1].day < days){
                for(let j=this.showData[this.showData.length-1].day+1;j<=days;j++){
                    backData.push({
                        day:j,
                        disable:true,
                        price:-1
                    })
                }
                this.showData = this.showData.concat(backData);
            }
            this.getFirstWeekDay();
            this.data.forEach((ele,i)=> {
                ele.dates.map(item=>{
                    item.month = ele.month;
                    item.year = ele.year;
                    item.yearSimple = ele.yearSimple;
                });
                if(i === index){
                    ele.isShow = true;
                    if(this.selectItem){
                        if(ele.year == this.defaultStartDate.year){//和默认年份相等
                            this.setMonthSelect(ele,this.defaultStartDate);
                        }
                        if(ele.year < this.defaultStartDate.year){//年份小于默认年份不可选
                            this.canSelect = false;
                            this.showData.map((item,k)=>{
                                item.disable = true;
                            });
                        }
                        if(ele.year > this.defaultStartDate.year){//年份大于默认年份不可选
                            this.showData.map((item,k)=>{
                                if(item.inventory){//有库存
                                    this.canSelect = true;
                                }else{
                                    item.disable = true;
                                }
                            });
                        }
                        if(ele.year == this.selectItem.year && ele.month == this.selectItem.month){//判断高亮
                            this.showData.map((item,k)=>{
                                if(item.day == this.selectItem.day&&item.inventory){
                                    this.selectIndex = k;
                                }
                            })
                        }
                    }else{//没有默认选中或者选中数据
                        this.canSelect = false;
                        this.showData.find((item,k)=>{
                            item.disable = true;
                        });
                    }
                };
            });
            this.firstEnter = false;
        },
        setMonthSelect(eleObj,secObj){//是否月份可选日历数据处理
            if(eleObj.month == this.defaultStartDate.month){//默认选中的日期当月
                this.showData.map((item,k)=>{
                    if(item.day < this.defaultStartDate.day){
                        item.disable = true;
                    }else{
                        if(item.inventory){//有一个库存即可选
                            this.canSelect = true;
                        }else{
                            item.disable = true;
                        }
                    }
                });
            }
            if(eleObj.month > this.defaultStartDate.month){//月份大于默认月份可选
                this.showData.map((item,k)=>{
                    if(item.inventory){//有库存
                        this.canSelect = true;
                    }else{
                        item.disable = true;
                    }
                });
            }
            if(eleObj.month < this.defaultStartDate.month){//月份小于默认月份不可选
                this.canSelect = false;
                this.showData.map((item,k)=>{
                    item.disable = true;
                });
            }
        },
        showFun(data,index){//显示日历逻辑处理
            if(this.firstEnter){
                if(this.defaultStartDate){
                    data.map((item,k)=>{
                        if(item.year == this.defaultStartDate.year && item.month == this.defaultStartDate.month){
                            this.tabActiveIndex = k;
                            this.tabScrollLeft = item.left-20;
                            this.showData = data[k].dates;
                            this.firstEnter = false;
                            this.activeYearMonth = {
                                year:data[k].year,
                                month:data[k].month,
                            }
                            this.makeMonthDya(k);
                        }
                    })
                }else{//没有默认选中 就显示数组第一条数据
                    this.showData = data[0].dates;
                    this.firstEnter = false;
                    this.activeYearMonth = {
                        year:data[0].year,
                        month:data[0].month,
                    }
                    this.tabActiveIndex = 0;
                    this.makeMonthDya(0);
                }
            }else{
                this.selectIndex = -1;
                this.showData = data[index].dates;
                this.activeYearMonth = {
                    year:data[index].year,
                    month:data[index].month,
                }
                this.makeMonthDya(index);
            }
            uni.hideLoading(); 
        },
        getYearMonthDay(date){
            let year = date.getFullYear();
            let month = date.getMonth();
            let day = date.getDate();
            let week = date.getDay();
            return {
                year,
                month,
                day,
                week
            };
        },
        getDate(year, month, day){
            return new Date(year, month, day)
        },
        fillOrder(){
            let month = this.selectItem.month>9?this.selectItem.month:`0${this.selectItem.month}`;
            let day = this.selectItem.day>9?this.selectItem.day:`0${this.selectItem.day}`;
            this.$api.checkInventory({
                merchId:this.merchId,
                count:this.selectNum,
                merchEffectDate:`${this.selectItem.year}-${month}-${day}`
            }).then(json=>{
                if(!json){//false库存不足
                    uni.showToast({
                        icon: 'none',
                        title: '库存不足，请重新选择'
                    });
                    setTimeout(()=>{
                        this.merchCalendar(0); 
                    },1000)
                }else{
                    let info ={
                        title : this.merchDetail.title,
                        price:this.selectItem.price,
                        vipPrice:this.selectItem.vipPrice,
                        merchEffectDate:`${this.selectItem.year}-${month}-${day}`,
                        showMerchEffectDate:`${this.selectItem.year}年${this.selectItem.month}月${this.selectItem.day}日`,
                        merchNum:this.selectNum,
                        orderPay:this.selectItem.price*this.selectNum,
                        vipOrderPay:this.selectItem.vipPrice*this.selectNum,
                        merchId:this.merchId,
                        inventory:this.selectItem.inventory
                    }
                    this.setCaleIndfo(info)
                    uni.navigateTo({
                        url: '/pages/fillOrder/fillOrder'
                    });
                }
            })
        },
        merchCalendar(index){//接口获取数据
            this.firstEnter = true;
            uni.showLoading({  
                title: '加载中'  
            });
            this.$api.merchCalendar({id:this.merchId||31}).then(json=>{
                this.data = json.priceMonths;
                this.merchDetail = json.merch;
                this.defaultStartDate = json.defaultStartDate;
                this.selectItem =  json.defaultStartDate;
                this.calcSize(json);
                setTimeout(()=>{
                    this.showFun(json.priceMonths,index);
                },400);
            })
        },
        //滚动到底部/右边触发
        scrolltolower() {
        },
        scroll(event) {
            //距离么个边界距离
            // console.log(event.detail)
        },
        calcSize(json){//计算滚动tab的高度
            setTimeout(()=>{
                uni.createSelectorQuery().selectAll('.scroll-view-item_H').boundingClientRect(rects=> {
                    rects.forEach((rect,index)=> {
                        this.data[index].left = rect.left;
                        this.data[index].width = rect.width;
                    })
                }).exec();
            },300);
        },
    },
}
</script>
<style lang='scss'>
    .fl {
		float: left;
		display: inline;
	}
	.fr {
		float: right;
		display: inline;
	}
	.clearfix:after {
		clear: both;
		content: ".";
		display: block;
		font-size: 0;
		height: 0;
		line-height: 0;
		visibility: hidden;
	}
	.clearfix {
		clear: both;
		zoom: 1;
    }
    .Ellipsis{
        overflow:hidden;
        white-space:nowrap;
        text-overflow:ellipsis;
    }
    .uni-container-calender{
        padding-bottom: 128upx;
        overflow-x: hidden;
        .cale-header{
            height: 84upx;
            line-height: 84upx;
            background: #F1F5F8;
            padding:0 24upx;
            font-size: 32upx;
            color: #262626;
            font-weight: bold;
        }
        .cale-content{
            .recomd-wapper{
                height: 93rpx;
                width: 100%;
                overflow: hidden;
                .selectionTab {
                    height: 75rpx;
                    padding:0 24upx;
                    box-sizing: border-box;
                    width: 100%;
                    background:#fff;
                    white-space: nowrap;
                    border-bottom: 1px solid #DDDDDD;
                    .scroll-view-item_H{
                        height: 75rpx;
                        line-height: 72rpx;
                        background: #fff;
                        display: inline-block;
                        position: relative;
                        font-size: 28upx;
                        color: #777777;
                        position: relative;
                        margin-right: 40upx;
                        &:last-child{
                            margin-right: 0;
                        }
                        &::before{
                            content: "";
                            display: inline-block;
                            background: #E25422;
                            border-radius: 100px 100px 0 0;
                            width: 64rpx;
                            height: 11rpx;
                            text-align: center;
                            display: none;
                            position: absolute;
                            bottom:-1rpx;
                            left: 50%;
                            transform: translateX(-50%);
                            -webkit-transform: translateX(-50%);
                        }
                    }
                    .Tabactive{
                        color: #262626;
                        &::before{
                            display: block;
                        }
                    }
                }
            }
            .cale-detail{
                padding: 0 24upx;
                padding-bottom: 20upx;
                border-bottom: 1px solid #DDDDDD;
                .cell{
                    width: 80upx;
                    height: 33upx;
                    display: inline-block;
                    font-size: 24upx;
                    color: #262626;
                    text-align: center;
                }
                .cale-week{
                    margin-right: 23upx;
                    &:nth-of-type(7n){
                        margin-right: 0;
                    }
                }
                .weekStyle{
                    color: #E25422;
                    .cell{
                        color: #E25422;
                    }
                }
                .cale-list{
                    .cale-li{
                        width: 80upx;
                        height: 90upx;
                        display: flex;
                        flex-direction: column;
                        margin-right: 23upx;
                        margin-top: 20upx;
                        &:nth-of-type(7n){
                            margin-right: 0;
                        }
                        .cell{
                            font-size: 28upx;
                        }
                        .price{
                            width: 100%;
                            height: 28upx;
                            display: inline-block;
                            font-size: 20upx;
                            color: #777777;
                            text-align: center;
                        }
                        .soldOut{
                            width: 100%;
                            height: 28upx;
                            display: inline-block;
                            font-size: 20upx;
                            color: #777777;
                            text-align: center;
                        }
                    }
                    .activeCela{
                        background: rgba(230, 81, 38,0.1);
                        border-radius: 4upx;
                    }
                    .disable{
                        color: #777777;
                        opacity: 0.5;
                    }
                }
            }
        }
        .cale-buy-container{
            padding: 0 24upx;
            padding-top: 24upx;
            h3{
                font-size: 32upx;
                color: #262626;  
                padding-bottom: 20upx;
            }
            .cale-count{
                display: flex;
                justify-content: space-between;
                font-size: 28upx;
                color: #262626;
                .cale-price{
                    .cale-buy-price{
                        font-size: 28upx;
                        color: #E65126;
                        margin: 0 20upx;
                    }
                    .cale-buy-vipPrice{
                        padding: 4upx 10upx;
                        font-size: 20upx;
                        color: #FFFFFF;
                        background: #F5A623;
                        border-radius: 4upx;
                        position: relative;
                        top: -1rpx;
                    }
                    .cale-buy-vip{
                        .vip-icon{
                            width: 92upx;
                            height: 36upx;
                            background: #F5A623;
                            border-radius: 4rpx;
                            line-height: 36upx;
                            text-align: center;
                            font-size: 20upx;
                            color: #FFFFFF;
                            display: inline-block;
                            position: relative;
                            top: -1rpx;
                            letter-spacing: 4rpx;
                        }  
                        .original-price{
                            margin-left: 22upx;
                            font-size: 20upx;
                            color: #777777;
                            text-decoration: line-through;
                        }
                    }
                }
                .cale-goods-num{
                    display: flex;
                    .num{
                        font-size: 28rpx;
                        color: #262626; 
                        height: 40upx;
                        margin:0 10upx;
                        position: relative;
                        top: -2rpx;
                        display: inline-block;
                        text-align: center;
                        
                    }
                    i{
                        display: block;
                        width: 36upx;
                        height: 36upx;
                        border-radius: 50%;
                        background: #EDEDED;
                        position: relative;
                        text-align: center;
                        line-height: 32upx;
                        font-size: 36rpx;
                        color:rgba(119, 119, 119,.8);
                    }
                }
            }
        }
        .cale-footer{
            width: 100%;
            height: 108upx;
            position:fixed;
            bottom: 0;
            .cale-select-info{
                display: inline-block;
                font-size: 28upx;
                color: #262626;
                background: #FFFFFF;
                box-shadow: 0 -10upx 16upx 0 rgba(164,164,164,0.20);
                width: calc(100% - 344upx);
                height: 108upx;
                line-height: 108upx;
                padding-left: 24upx;
            }
            .cale-next-btn{
                display: inline-block;
                background: #E25422;
                font-size: 32upx;
                color: #FFFFFF;
                width: 320upx;
                height: 108upx;
                line-height: 108upx;
                text-align: center;
            }
        }
    }
   
</style>
